package cn.itcast.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CommonConfig{

    public static final String DIRECT_EXCHANGE = "direct.exchange";
    public static final String DIRECT_ROUTE_KEY = "direct.key";
    public static final String DIRECT_QUEUE = "direct.queue";


    @Bean
    public DirectExchange directExchange(){
        //return new DirectExchange(DIRECT_EXCHANGE);//写法1：单参构造方法，默认持久化
        //return new DirectExchange(DIRECT_EXCHANGE,true,false);//写法2：单参构造方法，显示指定持久化
        return ExchangeBuilder.directExchange(DIRECT_EXCHANGE).durable(true).build();//写法3：使用ExchangeBuilder类，显示指定持久化
    }

    @Bean
    public Queue directQueue(){
        //return new Queue(DIRECT_QUEUE);//写法1：单参构造方法，默认持久化
        //return new Queue(DIRECT_QUEUE,true);//写法2：单参构造方法，默认持久化
        return QueueBuilder.durable(DIRECT_QUEUE).build();//写法3：使用QueueBuilder，显示指定持久化
    }

    @Bean
    public Binding bindDirectQueue(){
        return BindingBuilder.bind(directQueue()).to(directExchange()).with(DIRECT_ROUTE_KEY);
    }

    public static final String ERROR_EXCHANGE = "error.exchange";
    public static final String ERROR_ROUTE_KEY = "error.key";
    public static final String ERROR_QUEUE = "error.queue";

    @Bean
    public DirectExchange errorExchange(){
        return new DirectExchange(ERROR_EXCHANGE);
    }

    @Bean
    public Queue errorQueue(){
        return new Queue(ERROR_QUEUE);
    }
    /*@Bean
    public Binding bindErrorQueue(Queue errorQueue,DirectExchange errorExchange){
        return BindingBuilder.bind(errorQueue).to(errorExchange).with(ERROR_ROUTE_KEY);
    }*/

    @Bean
    public Binding bindErrorQueue(){
        return BindingBuilder.bind(errorQueue()).to(errorExchange()).with(ERROR_ROUTE_KEY);
    }

    @Bean
    public DirectExchange ttlExchange(){
        return new DirectExchange("ttl.exchange");
    }

    @Bean
    public Queue ttlQueue(){
        return QueueBuilder.durable("ttl.queue")
                .ttl(10000) //队列的过期时间，单位毫秒
                .deadLetterExchange("dl.exchange") //死信交换机名称
                .deadLetterRoutingKey("dl.key") //死信路由KEY
                .build();
    }

    @Bean
    public Binding bindTtlQueue(){
        return BindingBuilder.bind(ttlQueue()).to(ttlExchange()).with("ttl.key");
    }
}
